import React from 'react';
import PropTypes from 'prop-types';
import { stripesConnect } from '@folio/stripes/core';

import EditForm from './edit-form';

class FormSachet extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: '',
      editParams: {},
      exitFlag: true,
      operator: {}
    };
  }

  static manifest = Object.freeze({
    httpEquipmentInvoke: {
      type: 'okapi',
      accumulate: true,
      path: 'party/auxiliary'
    },
    checkInputInvoke: {
      type: 'okapi',
      accumulate: true,
      path: 'party/auxiliary'
    },
    imageUploadHttpInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/image'
    }
  });

  static propTypes = {
    stripes: PropTypes.shape({
      logger: PropTypes.object,
      okapi:PropTypes.object
    }).isRequired,
    mutator: PropTypes.shape({
      httpEquipmentInvoke: PropTypes.shape({
        POST: PropTypes.func.isRequired
      }),
      checkInputInvoke: PropTypes.shape({
        GET: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired
      }),
      imageUploadHttpInvoke: {
        POST: PropTypes.func.isRequired,
        PUT: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired
      }
    }).isRequired,
    toModel:PropTypes.func,
    removeTopMenu:PropTypes.func,
    params:PropTypes.object,
    matchPath:PropTypes.string,
    name:PropTypes.string,
  };

  // eslint-disable-next-line react/sort-comp
  editCommit = ({ requestPreferences, creds, ...formData }) => {
    if (formData) {
     
      formData.amount = parseInt(formData.amount);

      formData.state = parseInt(formData.state);
      formData.operator = this.state.operator;
      delete formData.operator.addresses;
      delete formData.operator.preferredContactTypeId;
      delete formData.operator.servicePoints;
      delete formData.operator.curServicePoint;
      delete formData.operator.dateOfBirth;
      if (formData.id) {
        const amount = formData.amount;
        const editParams = this.state.editParams;
        const oldAmount = editParams.amount;
        const oldRemainder = editParams.remainder;
        // eslint-disable-next-line radix
        if (parseInt(amount) !== parseInt(oldAmount)) {
          // eslint-disable-next-line radix
          const oldDifference = parseInt(oldAmount) - parseInt(oldRemainder);
          const formDataDifference =
            // eslint-disable-next-line radix
            parseInt(formData.amount) - parseInt(formData.remainder);
          // eslint-disable-next-line radix
          if (parseInt(amount) > parseInt(oldAmount)) {
            // eslint-disable-next-line radix
            const addDifference = parseInt(amount) - parseInt(oldAmount);
            // eslint-disable-next-line radix
            const newremainder = parseInt(formData.remainder) + addDifference;
            // eslint-disable-next-line radix
            if (newremainder > parseInt(amount)) {
              // eslint-disable-next-line radix
              formData.remainder = parseInt(amount);
            } else {
              formData.remainder = newremainder;
            }
          } else {
            // eslint-disable-next-line radix
            const reDifference = parseInt(oldAmount) - parseInt(amount);
            // eslint-disable-next-line radix
            const newDifference = parseInt(formData.remainder) - reDifference;
            if (newDifference < 0) {
              formData.remainder = 0;
            } else {
              formData.remainder = newDifference;
            }
          }
        }
        this.update(formData);
      } else if (!formData.id) {
        this.add(formData);
      }
    }
  };

  add = data => {
    const {   intl } = this.props;
    const { currentUser } = this.props.okapi;
    const { POST } = this.props.mutator.httpEquipmentInvoke;
    data.isDel = 0;
    data.remainder = data.amount;
    data.author = currentUser.username;

    POST(data).then(response => {
      // eslint-disable-next-line no-alert
      alert(intl.formatMessage({id:"ui-party.other.saved.successfully"}));
      this.cancel(false);
    });
  };

  update = data => {
    const { PUT } = this.props.mutator.httpEquipmentInvoke;
    const {   intl } = this.props;
    PUT(data).then(response => {
      // eslint-disable-next-line no-alert
      alert(intl.formatMessage({id:"ui-party.other.saved.successfully"}));
      this.cancel(false);
    });
  };

  cancel = (flag = true) => {
    const { removeTopMenu, matchPath } = this.props;
    removeTopMenu(matchPath, flag);
  };

  componentDidMount() {
    if (!!this.props.params && !!this.props.params.id) {
      const params = this.props.params;
      if (params.id) {
        const id = params.id;
        this.initData(id);
      }
    }
    const { currentUser } = this.props.stripes.okapi;
    if (currentUser) {
      this.setState({
        operator: currentUser
      });
    }
  }

  initData = param => {
    const get = this.props.mutator.httpEquipmentInvoke.GET;

    get({ path: `party/auxiliary/${param}` }).then(res => {
      if (res) {
        const editParams = res;
        this.setState({
          editParams,
          // eslint-disable-next-line react/no-unused-state
          id: param
        });
      }
    });
  };

  render() {
    return (
      <EditForm
        onSubmit={this.editCommit}
        initialValues={this.state.editParams}
        cancel={this.cancel}
        exitFlag={this.state.exitFlag}
        httpValidatorInvoke={this.props.mutator.httpEquipmentInvoke}
        imageUploadHttpInvoke={this.props.mutator.imageUploadHttpInvoke}
        toModel={this.props.toModel}
        removeTopMenu={this.props.removeTopMenu}
        stripes={this.props.stripes}
        form={this.props.name}
      />
    );
  }
}

export default stripesConnect(FormSachet);
